package com.logic.landseaserver.models.rental.service;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.system.service.IConfigurationService;
import com.logic.system.service.impl.ConfigurationService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.domain.Code;
import com.logic.common.exception.BusinessException;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.RentalResultCode;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.JsonObjectUtils;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.domain.Order;
import com.logic.landseaserver.domain.Project;
import com.logic.landseaserver.domain.Room;
import com.logic.landseaserver.models.payment.config.ShijiPaymentConfig;
import com.logic.landseaserver.models.rental.bean.DataResp;
import com.logic.landseaserver.models.rental.bean.DataVerifyReq;
import com.logic.landseaserver.models.rental.bean.PrjRoomDataReq;
import com.logic.landseaserver.models.rental.bean.ProjectDataBase;
import com.logic.landseaserver.models.rental.bean.ProjectResp;
import com.logic.landseaserver.models.rental.bean.RoomDataBase;
import com.logic.landseaserver.models.rental.bean.RoomResp;
import com.logic.landseaserver.models.rental.bean.RoomType;
import com.logic.landseaserver.models.rental.bean.RoomTypeDataBase;
import com.logic.landseaserver.models.rental.bean.UploadOrderInfoReq;
import com.logic.landseaserver.models.rental.bean.UploadVerifyReq;
import com.logic.landseaserver.models.rental.util.YingShiDesUtil;
import com.logic.landseaserver.models.rental.util.YingShiSignVerifyUtil;
import com.logic.landseaserver.persistence.read.OrderReadMapper;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.persistence.read.RoomReadMapper;
import com.logic.landseaserver.persistence.read.RoomTypeReadMapper;
import com.logic.landseaserver.persistence.write.OrderWriteMapper;
import com.logic.landseaserver.ws.dto.OrderDTO;
import com.logic.landseaserver.ws.dto.ProjectDetailDTO;
import com.logic.system.domain.SystemFile;
import com.logic.system.persistence.read.CodeReadMapper;
import com.logic.system.service.impl.AddressService;
import com.logic.system.service.impl.FileService;
import com.logic.system.ws.dto.AddressDto;

@Service
public class RentalService 
{
	private static final Logger logger = LoggerFactory.getLogger(RentalService.class);

	@Autowired
	private ProjectReadMapper projectReadMapper;

	@Autowired
	private FileService fileService;

	@Autowired
	private CodeReadMapper codeReadMapper;

	@Autowired
	private RoomReadMapper roomReadMapper;

	@Autowired
	private RoomTypeReadMapper roomTypeReadMapper;

	@Autowired
	private OrderReadMapper orderReadMapper;

	@Autowired
	private OrderWriteMapper orderWriteMapper;

	@Autowired
	private AddressService addressService;

	@Autowired
	private SendMsgConfiguration sendMsgConfiguration;

	@Autowired
	private ShijiPaymentConfig shijiPaymentConfig;

	@Autowired
	private IConfigurationService configurationService;

	public Map<String, List<Map<String, Object>>> syncPrjRoomData(PrjRoomDataReq req) throws LandseaException
	{
		try
		{
			Map<String, List<Map<String, Object>>> resultMap = new HashMap<String, List<Map<String, Object>>>();
			DataResp resultResp = new DataResp();
			if (StringUtils.isEmpty(req.getUpdateTime())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510003);
			}
			String time = req.getUpdateTime();
			List<ProjectDataBase> projectDataBases = projectReadMapper.selectForYingShi(time);
			List<ProjectResp> projects = getProjects(projectDataBases);
			resultResp.setProject(projects);

			List<RoomDataBase> roomDataBases = roomReadMapper.selectForYingShi(time);
			List<RoomResp> rooms = getRooms(roomDataBases);
			resultResp.setRoom(rooms);

			List<RoomTypeDataBase> roomTypeDataBases = roomTypeReadMapper.selectForYingShi(time);
			List<RoomType> roomTypes = getRoomTypes(roomTypeDataBases);
			resultResp.setRoomType(roomTypes);

			resultMap = coverFromResultResp(resultResp);
			return resultMap;
		}
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			logger.error("集中式房源信息获取失败.", e);
			throw LandseaException.createException(RentalResultCode.E011510001, e);
		}
	}

	private Map<String, List<Map<String, Object>>> coverFromResultResp(DataResp resultResp) 
	{
		Map<String, List<Map<String, Object>>> mapData = new HashMap<String, List<Map<String, Object>>>();
		DecimalFormat df = new DecimalFormat("0.00");
		if (CollectionUtils.isNotEmpty(resultResp.getProject())) 
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();

			mapData.put("project", maps);
			for (ProjectResp project : resultResp.getProject()) 
			{
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("address", project.getAddress() == null ? "" : project.getAddress());
				if (null != project.getProjectId()) 
				{
					data.put("projectId", project.getProjectId());
				}
				if (null != project.getDeleted()) 
				{
					data.put("deleted", project.getDeleted());
				}
				data.put("prj_code", project.getPrj_code() == null ? "" : project.getPrj_code());
				data.put("prj_name", project.getPrj_name() == null ? "" : project.getPrj_name());
				data.put("communityName", project.getCommunityName() == null ? "" : project.getCommunityName());
				if (null != project.getDistrict_user_id()) 
				{
					data.put("district_user_id", project.getDistrict_user_id());
				}
				data.put("district_user_name", project.getDistrict_user_name() == null ? "" : project.getDistrict_user_name());
				if (null != project.getHousekeeper_user_id()) 
				{
					data.put("housekeeper_user_id", project.getHousekeeper_user_id());
				}
				data.put("housekeeper_user_name", project.getHousekeeper_user_name() == null ? "" : project.getHousekeeper_user_name());
				if (null != project.getIn_charge_user_id()) 
				{
					data.put("in_charge_user_id", project.getIn_charge_user_id());
				}
				data.put("in_charge_user_name", project.getIn_charge_user_name() == null ? "" : project.getIn_charge_user_name());
				data.put("area_code", project.getArea_code() == null ? "" : project.getArea_code());
				data.put("province", project.getProvince() == null ? "" : project.getProvince());
				data.put("district_zh", project.getDistrict_zh() == null ? "" : project.getDistrict_zh());
				data.put("area_zh", project.getArea_zh() == null ? "" : project.getArea_zh());
				data.put("organization_zh", project.getOrganization_zh() == null ? "" : project.getOrganization_zh());
				data.put("source_type", project.getSource_type() == null ? "" : project.getSource_type());
				data.put("online_time", project.getOnline_time() == null ? "" : project.getOnline_time());

				if (null != project.getTotal_apartments_count()) 
				{
					data.put("total_apartments_count", project.getTotal_apartments_count());
				}
				data.put("traffic_subway", project.getTraffic_subway() == null ? "" : project.getTraffic_subway());
				data.put("traffic_bus", project.getTraffic_bus() == null ? "" : project.getTraffic_bus());
				data.put("traffic_road", project.getTraffic_road() == null ? "" : project.getTraffic_road());
				data.put("traffic_info", project.getTraffic_info() == null ? "" : project.getTraffic_info());
				if (null != project.getPrice()) 
				{
					data.put("price", df.format(project.getPrice()));
				}

				if (null != project.getIs_classics()) 
				{
					data.put("is_classics", project.getIs_classics());
				}
				data.put("brief_desc", project.getBrief_desc() == null ? "" : project.getBrief_desc());
				data.put("status", project.getStatus() == null ? "" : project.getStatus());
				data.put("public_status", project.getPublic_status() == null ? "" : project.getPublic_status());
				data.put("manage_status", project.getManage_status() == null ? "" : project.getManage_status());
				data.put("telephone", project.getTelephone() == null ? "" : project.getTelephone());
				data.put("cover_image", project.getCover_image() == null ? "" : project.getCover_image());
				data.put("detail_images", project.getDetail_images() == null ? "" : project.getDetail_images());
				data.put("public_images", project.getPublic_images() == null ? "" : project.getPublic_images());
				data.put("public_desc", project.getPublic_desc() == null ? "" : project.getPublic_desc());
				data.put("whole_scene_url", project.getWhole_scene_url() == null ? "" : project.getWhole_scene_url());
				data.put("commercial_facility", project.getCommercial_facility() == null ? "" : project.getCommercial_facility());
				data.put("cost_type", project.getCost_type() == null ? "" : project.getCost_type());
				if (null != project.getDeposit_amount()) 
				{
					data.put("deposit_amount", df.format(project.getDeposit_amount()));
				}

				data.put("term_of_validity", project.getTerm_of_validity() == null ? "" : project.getTerm_of_validity());
				data.put("payment_mode", project.getPayment_mode() == null ? "" : project.getPayment_mode());
				data.put("lease", project.getLease() == null ? "" : project.getLease());
				if (null != project.getWater_price()) 
				{
					data.put("water_price", df.format(project.getWater_price()));
				}
				if (null != project.getElectric_price()) 
				{
					data.put("electric_price", df.format(project.getElectric_price()));
				}
				if (null != project.getGas_price()) 
				{
					data.put("gas_price", df.format(project.getGas_price()));
				}
				if (null != project.getHot_water_price()) 
				{
					data.put("hot_water_price", df.format(project.getHot_water_price()));
				}
				if (null != project.getPark_price()) 
				{
					data.put("park_price", df.format(project.getPark_price()));
				}
				if (null != project.getAir_conditioner_price()) 
				{
					data.put("air_conditioner_price", df.format(project.getAir_conditioner_price()));
				}
				if (null != project.getHeating_price()) 
				{
					data.put("heating_price", df.format(project.getHeating_price()));
				}
				data.put("competition", project.getCompetition() == null ? "" : project.getCompetition());
				if (null != project.getDeposit_water()) 
				{
					data.put("deposit_water", df.format(project.getDeposit_water()));
				}
				data.put("contract_name", project.getContract_name() == null ? "" : project.getContract_name());
				data.put("contract_phone", project.getContract_phone() == null ? "" : project.getContract_phone());
				data.put("contract_address", project.getContract_address() == null ? "" : project.getContract_address());
				data.put("merchant_id", project.getMerchant_id() == null ? "" : project.getMerchant_id());

				data.put("merchant_name", project.getMerchant_name() == null ? "" : project.getMerchant_name());
				data.put("merchant_abbreviation", project.getMerchant_abbreviation() == null ? "" : project.getMerchant_abbreviation());
				data.put("created_dtm", project.getCreated_dtm() == null ? "" : project.getCreated_dtm());
				data.put("last_modified_dtm", project.getLast_modified_dtm() == null ? "" : project.getLast_modified_dtm());					
				maps.add(data);
			}
		}
		else
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();
			mapData.put("project", maps);
		}
		if (CollectionUtils.isNotEmpty(resultResp.getRoom())) 
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();

			mapData.put("room", maps);
			for (RoomResp room : resultResp.getRoom()) 
			{
				Map<String, Object> data = new HashMap<String, Object>();

				if (null != room.getRoomId()) 
				{
					data.put("roomId", room.getRoomId());
				}
				if (null != room.getDeleted()) 
				{
					data.put("deleted", room.getDeleted());
				}
				if (null != room.getProjectId()) 
				{
					data.put("projectId", room.getProjectId());
				}				
				data.put("room_code", room.getRoom_code() == null ? "" : room.getRoom_code());
				data.put("build_num", room.getBuild_num() == null ? "" : room.getBuild_num());
				data.put("floor_num", room.getFloor_num() == null ? "" : room.getFloor_num());
				data.put("unit_num", room.getUnit_num() == null ? "" : room.getUnit_num());
				data.put("house_num", room.getHouse_num() == null ? "" : room.getHouse_num());

				if (null != room.getBuild_area()) 
				{
					data.put("build_area", df.format(room.getBuild_area()));
				}
				if (null != room.getInside_area()) 
				{
					data.put("inside_area", df.format(room.getInside_area()));
				}

				data.put("rent", room.getRent() == null ? 0 : room.getRent());


				if (null != room.getOriginal_price()) 
				{
					data.put("original_price", df.format(room.getOriginal_price()));
				}

				if (null != room.getProperty_fee()) 
				{
					data.put("property_fee", df.format(room.getProperty_fee()));
				}
				data.put("rent_type", room.getRent_type() == null ? "" : room.getRent_type());
				if (null != room.getRoomStyleId()) 
				{
					data.put("roomStyleId", room.getRoomStyleId());
				}
				data.put("room_type", room.getRoom_type() == null ? "" : room.getRoom_type());
				data.put("tags", room.getTags() == null ? "" : room.getTags());
				data.put("housekeeper", room.getHousekeeper() == null ? "" : room.getHousekeeper());
				data.put("status", room.getStatus() == null ? "" : room.getStatus());
				data.put("append_status", room.getAppend_status() == null ? "" : room.getAppend_status());

				if (null != room.getMax_resident()) 
				{
					data.put("max_resident", room.getMax_resident());
				}
				data.put("description", room.getDescription() == null ? "" : room.getDescription());
				data.put("able_check_in_time", room.getAble_check_in_time() == null ? "" : room.getAble_check_in_time());
				data.put("room_style", room.getRoom_style() == null ? "" : room.getRoom_style());
				data.put("room_divice", room.getRoom_divice() == null ? "" : room.getRoom_divice());
				data.put("room_direction", room.getRoom_direction() == null ? "" : room.getRoom_direction());
				data.put("occupy_reason", room.getOccupy_reason() == null ? "" : room.getOccupy_reason());

				if (null != room.getDirty_flag()) 
				{
					data.put("dirty_flag", room.getDirty_flag());
				}
				if (null != room.getSigned()) 
				{
					data.put("signed", room.getSigned());
				}
				if (null != room.getOffrent_status()) 
				{
					data.put("offrent_status", room.getOffrent_status());
				}
				data.put("created_dtm", room.getCreated_dtm() == null ? "" : room.getCreated_dtm());
				data.put("last_modified_dtm", room.getLast_modified_dtm() == null ? "" : room.getLast_modified_dtm());
				maps.add(data);
			}
		}
		else
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();
			mapData.put("room", maps);

		}
		if (CollectionUtils.isNotEmpty(resultResp.getRoomType())) 
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();

			mapData.put("roomType", maps);
			for (RoomType roomType : resultResp.getRoomType()) 
			{
				Map<String, Object> data = new HashMap<String, Object>();

				if (null != roomType.getRoomStyleId()) 
				{
					data.put("roomStyleId", roomType.getRoomStyleId());
				}
				if (null != roomType.getDeleted()) 
				{
					data.put("deleted", roomType.getDeleted());
				}
				if (null != roomType.getProjectId()) 
				{
					data.put("projectId", roomType.getProjectId());
				}				
				data.put("type_code", roomType.getType_code() == null ? "" : roomType.getType_code());
				data.put("type_code_zh", roomType.getType_code_zh() == null ? "" : roomType.getType_code_zh());


				if (null != roomType.getPrice()) 
				{
					data.put("price", df.format(roomType.getPrice()));
				}

				data.put("detail_images", roomType.getDetail_images() == null ? "" : roomType.getDetail_images());
				data.put("facility", roomType.getFacility() == null ? "" : roomType.getFacility());

				data.put("created_dtm", roomType.getCreated_dtm() == null ? "" : roomType.getCreated_dtm());
				data.put("last_modified_dtm", roomType.getLast_modified_dtm() == null ? "" : roomType.getLast_modified_dtm());
				maps.add(data);
			}
		}
		else
		{
			List<Map<String, Object>> maps  = new ArrayList<Map<String, Object>>();
			mapData.put("roomType", maps);
		}

		return mapData;
	}

	private List<RoomType> getRoomTypes(List<RoomTypeDataBase> roomTypeDataBases) throws BusinessException {
		List<RoomType> resultRoomTypes = new ArrayList<RoomType>();
		if (CollectionUtils.isNotEmpty(roomTypeDataBases)) 
		{
			for (RoomTypeDataBase dataBase : roomTypeDataBases) 
			{
				RoomType roomType = coverByRoomTypeDataBase(dataBase);
				//图片，多图数组
				if (StringUtils.isNotEmpty(dataBase.getDetail_images())) 
				{
					String []detailImages = dataBase.getDetail_images().split(",");
					StringBuffer buffer = new StringBuffer();
					for (String str : detailImages) 
					{
						try 
						{
							Integer id = Integer.parseInt(str);
							SystemFile file = (SystemFile)fileService.get(id);
							if (null != file && null != file.getFullPath()) 
							{
								buffer.append(file.getFullPath());
								buffer.append(",");
							}
							
						} 
						catch (Exception e) 
						{
							e.printStackTrace();
						}
						
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						roomType.setDetail_images(array);
					}
				}
				//房型设备，多个数组：
				//床头柜、衣柜、电视、鞋柜、穿衣镜、沙发、懒人沙发、茶几、
				//餐桌、餐椅、电视柜、空调、窗帘、晾衣架、热水器、微波炉、橱柜、
				//灶具、油烟机、盥洗台、书架、淋浴、大床、电磁炉、床、桌子、独立卫浴、双床、冰箱、写字桌、写字椅、洗衣机
				if (StringUtils.isNotEmpty(dataBase.getFacility())) 
				{
					String []costTypes = dataBase.getFacility().split(",");
					List<Code> facilityCodes = codeReadMapper.selectCostType("_LD");
					StringBuffer buffer = new StringBuffer();
					if (CollectionUtils.isNotEmpty(facilityCodes)) 
					{
						for (Code code : facilityCodes) 
						{
							for (String str : costTypes) 
							{
								if (str.equals(code.getCode())) 
								{
									buffer.append(code.getCodeDescZh());
									buffer.append(",");
								}
							}
						}
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						roomType.setFacility(array);
					}
				}
				resultRoomTypes.add(roomType);
			}			
		}
		return resultRoomTypes;
	}

	private RoomType coverByRoomTypeDataBase(RoomTypeDataBase dataBase) {
		RoomType roomType = new RoomType();
		roomType.setCreated_dtm(dataBase.getCreated_dtm());
		roomType.setDeleted(dataBase.getDeleted());
		roomType.setLast_modified_dtm(dataBase.getLast_modified_dtm());
		roomType.setPrice(dataBase.getPrice());
		roomType.setProjectId(dataBase.getProjectId());
		roomType.setRoomStyleId(dataBase.getRoomStyleId());
		roomType.setType_code(dataBase.getType_code());
		roomType.setType_code_zh(dataBase.getType_code_zh());
		return roomType;
	}

	private List<RoomResp> getRooms(List<RoomDataBase> roomDataBases) 
	{
		List<RoomResp> resultRooms = new ArrayList<RoomResp>();
		if (CollectionUtils.isNotEmpty(roomDataBases)) 
		{
			for (RoomDataBase dataBase : roomDataBases) 
			{
				RoomResp room = coverByRoomDataBase(dataBase);
				//房间设施，多个数组存放：床头柜、衣柜、电视、鞋柜、穿衣镜、沙发、
				//懒人沙发、茶几、餐桌、餐椅、电视柜、空调、窗帘、晾衣架、热水器、
				//微波炉、橱柜、灶具、油烟机、盥洗台、书架、淋浴、大床、电磁炉、床、桌子、独立卫浴、双床、冰箱、写字桌、写字椅、洗衣机
				if (StringUtils.isNotEmpty(dataBase.getRoom_divice())) 
				{
					String []roomDivices = dataBase.getRoom_divice().split(",");
					List<Code> roomDiviceCodes = codeReadMapper.selectCostType("_LD");
					StringBuffer buffer = new StringBuffer();
					if (CollectionUtils.isNotEmpty(roomDiviceCodes)) 
					{
						for (Code code : roomDiviceCodes) 
						{
							for (String str : roomDivices) 
							{
								if (str.equals(code.getCode())) 
								{
									buffer.append(code.getCodeDescZh());
									buffer.append(",");
								}
							}
						}
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						room.setRoom_divice(array);
					}
				}
				resultRooms.add(room);
			}			
		}
		return resultRooms;
	}

	private RoomResp coverByRoomDataBase(RoomDataBase dataBase) {
		RoomResp room = new RoomResp();
		room.setAble_check_in_time(dataBase.getAble_check_in_time());
		room.setAppend_status(dataBase.getAppend_status());
		room.setBuild_area(dataBase.getBuild_area());
		room.setBuild_num(dataBase.getBuild_num());
		room.setCreated_dtm(dataBase.getCreated_dtm());
		room.setDeleted(dataBase.getDeleted());
		room.setDescription(dataBase.getDescription());
		room.setDirty_flag(dataBase.getDirty_flag());
		room.setFloor_num(dataBase.getFloor_num());
		room.setHouse_num(dataBase.getHouse_num());
		room.setHousekeeper(dataBase.getHousekeeper());
		room.setInside_area(dataBase.getInside_area());
		room.setLast_modified_dtm(dataBase.getLast_modified_dtm());
		room.setMax_resident(dataBase.getMax_resident());
		room.setOccupy_reason(dataBase.getOccupy_reason());
		room.setOffrent_status(dataBase.getOffrent_status());
		room.setOriginal_price(dataBase.getOriginal_price());
		room.setProjectId(dataBase.getProjectId());
		room.setProperty_fee(dataBase.getProperty_fee());
		room.setRent(dataBase.getRent());
		room.setRent_type(dataBase.getRent_type());
		room.setRoom_code(dataBase.getRoom_code());
		room.setRoom_direction(dataBase.getRoom_direction());
		room.setRoom_style(dataBase.getRoom_style());
		room.setRoom_type(dataBase.getRoom_type());
		room.setRoomId(dataBase.getRoomId());
		room.setSigned(dataBase.getSigned());
		room.setStatus(dataBase.getStatus());
		room.setTags(dataBase.getTags());
		room.setUnit_num(dataBase.getUnit_num());
		room.setRoomStyleId(dataBase.getRoomStyleId());
		return room;
	}

	private List<ProjectResp> getProjects(List<ProjectDataBase> projectDataBases) throws BusinessException
	{
		List<ProjectResp> resultProjects = new ArrayList<ProjectResp>();
		if (CollectionUtils.isNotEmpty(projectDataBases)) 
		{
			for (ProjectDataBase dataBase : projectDataBases) 
			{
				ProjectResp project = coverByProjectDataBase(dataBase);
				//主图片URL地址，只有一张
				if (null != dataBase.getCoverImage()) 
				{
					Integer coverImage = dataBase.getCoverImage();
					SystemFile file = (SystemFile)fileService.get(coverImage);
					if (null != file && null != file.getFullPath()) 
					{
						project.setCover_image(file.getFullPath());
					}
				}
				//详情图片URL地址，可以多张，数组存放
				if (StringUtils.isNotEmpty(dataBase.getDetailImages())) 
				{
					String []detailImages = dataBase.getDetailImages().split(",");
					StringBuffer buffer = new StringBuffer();
					for (String str : detailImages) 
					{
						try 
						{
							Integer id = Integer.parseInt(str);

							SystemFile file = (SystemFile)fileService.get(id);
							if (null != file && null != file.getFullPath()) 
							{
								buffer.append(file.getFullPath());
								buffer.append(",");
							}
						} 
						catch (Exception e) 
						{
							e.printStackTrace();
						}
						

					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						project.setDetail_images(array);
					}
				}
				//公区图片URL地址，可以多张，数组存放
				if (StringUtils.isNotEmpty(dataBase.getPublicImages())) 
				{
					String []publicImages = dataBase.getPublicImages().split(",");
					StringBuffer buffer = new StringBuffer();
					for (String str : publicImages) 
					{
						try 
						{
							Integer id = Integer.parseInt(str);
							SystemFile file = (SystemFile)fileService.get(id);
							if (null != file && null != file.getFullPath()) 
							{
								buffer.append(file.getFullPath());
								buffer.append(",");
							}
						} 
						catch (Exception e) 
						{
							e.printStackTrace();
						}
						
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						project.setPublic_images(array);
					}
				}
				//费用类型（多个），数组存放：水费、电费、 燃气费、 热水费、 停车费、空调费、采暖费、房租 、服务费
				if (StringUtils.isNotEmpty(dataBase.getCostType())) 
				{
					String []costTypes = dataBase.getCostType().split(",");
					List<Code> costTypeCodes = codeReadMapper.selectCostType("_CTBI");
					StringBuffer buffer = new StringBuffer();
					if (CollectionUtils.isNotEmpty(costTypeCodes)) 
					{
						for (Code code : costTypeCodes) 
						{
							for (String str : costTypes) 
							{
								if (str.equals(code.getCode())) 
								{
									buffer.append(code.getCodeDescZh());
									buffer.append(",");
								}
							}
						}
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						project.setCost_type(array);
					}
				}
				//付租方式(多个)数组存放：
				//付一押二、付三押二、付三押一、付六押一、全额付清、付一押一、付六押二、付二押二、付二押一
				if (StringUtils.isNotEmpty(dataBase.getPaymentMode()))
				{
					String []paymentModes = dataBase.getPaymentMode().split(",");
					List<Code> paymentModeCodes = codeReadMapper.selectCostType("_PAMO");
					StringBuffer buffer = new StringBuffer();
					if (CollectionUtils.isNotEmpty(paymentModeCodes)) 
					{
						for (Code code : paymentModeCodes) 
						{
							for (String str : paymentModes) 
							{
								if (str.equals(code.getCode())) 
								{
									buffer.append(code.getCodeDescZh());
									buffer.append(",");
								}
							}
						}
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						project.setPayment_mode(array);
					}
				}
				//租期 (多个)数组存放：
				//1个月、10个月、11个月、12个月、2个月、3个月、4个月、5个月、6个月、7个月、8个月、9个月、其他
				//注：其他时可选择按天
				if (StringUtils.isNotEmpty(dataBase.getLease()))
				{
					String []lease = dataBase.getLease().split(",");
					List<Code> leaseCodes = codeReadMapper.selectCostType("_LEAS");
					StringBuffer buffer = new StringBuffer();
					if (CollectionUtils.isNotEmpty(leaseCodes)) 
					{
						for (Code code : leaseCodes) 
						{
							for (String str : lease) 
							{
								if (str.equals(code.getCode())) 
								{
									buffer.append(code.getCodeDescZh());
									buffer.append(",");
								}
							}
						}
					}
					if (null != buffer) 
					{
						String[] array = buffer.toString().split(",");
						project.setLease(array);
					}
				}
				resultProjects.add(project);
			}			
		}
		return resultProjects;
	}

	private ProjectResp coverByProjectDataBase(ProjectDataBase dataBase)
	{
		ProjectResp project = new ProjectResp();
		project.setAddress(dataBase.getAddress());
		project.setAir_conditioner_price(dataBase.getAir_conditioner_price());
		project.setArea_code(dataBase.getArea_code());
		project.setArea_zh(dataBase.getArea_zh());
		project.setDistrict_zh(dataBase.getDistrict_zh());
		project.setProvince(dataBase.getProvince());
		project.setBrief_desc(dataBase.getBrief_desc());
		project.setCommercial_facility(dataBase.getCommercial_facility());
		project.setCompetition(dataBase.getCompetition());
		project.setContract_address(dataBase.getContract_address());
		project.setContract_name(dataBase.getContract_name());
		project.setContract_phone(dataBase.getContract_phone());
		project.setCommunityName(dataBase.getPrj_name());
		project.setCreated_dtm(dataBase.getCreated_dtm());
		project.setDeleted(dataBase.getDeleted());
		project.setDeposit_amount(dataBase.getDeposit_amount());
		project.setDeposit_water(dataBase.getDeposit_water());

		project.setDistrict_user_id(dataBase.getDistrict_user_id());
		project.setDistrict_user_name(dataBase.getDistrict_user_name());
		project.setElectric_price(dataBase.getElectric_price());
		project.setGas_price(dataBase.getGas_price());
		project.setHeating_price(dataBase.getHeating_price());
		project.setHot_water_price(dataBase.getHot_water_price());
		project.setHousekeeper_user_id(dataBase.getHousekeeper_user_id());
		project.setHousekeeper_user_name(dataBase.getHousekeeper_user_name());
		project.setIn_charge_user_id(dataBase.getIn_charge_user_id());
		project.setIn_charge_user_name(dataBase.getIn_charge_user_name());
		project.setIs_classics(dataBase.getIs_classics());
		project.setLast_modified_dtm(dataBase.getLast_modified_dtm());

		project.setManage_status(dataBase.getManage_status());
		project.setMerchant_abbreviation(dataBase.getMerchant_abbreviation());
		project.setMerchant_id(dataBase.getMerchant_id());
		project.setMerchant_name(dataBase.getMerchant_name());
		project.setOnline_time(dataBase.getOnline_time());
		project.setOrganization_zh(dataBase.getOrganization_zh());
		project.setPark_price(dataBase.getPark_price());

		project.setPrice(dataBase.getPrice());
		project.setPrj_code(dataBase.getPrj_code());
		project.setPrj_name(dataBase.getPrj_name());
		project.setProjectId(dataBase.getProjectId());
		project.setPublic_desc(dataBase.getPublic_desc());

		project.setPublic_status(dataBase.getPublic_status());
		project.setSource_type(dataBase.getSource_type());
		project.setStatus(dataBase.getStatus());
		project.setTelephone(dataBase.getTelephone());
		project.setTerm_of_validity(dataBase.getTerm_of_validity());
		project.setTotal_apartments_count(dataBase.getTotal_apartments_count());
		project.setTraffic_bus(dataBase.getTraffic_bus());
		project.setTraffic_info(dataBase.getTraffic_info());
		project.setTraffic_road(dataBase.getTraffic_road());
		project.setTraffic_subway(dataBase.getTraffic_subway());
		project.setWater_price(dataBase.getWater_price());
		project.setWhole_scene_url(dataBase.getWhole_scene_url());
		return project;
	}

	public void uploadOrderInfo(UploadOrderInfoReq req) throws LandseaException
	{
		try
		{
			if (StringUtils.isEmpty(req.getOrder_person_name())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510004);
			}
			if (StringUtils.isEmpty(req.getOrder_person_sex())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510005);
			}
			if (StringUtils.isEmpty(req.getOrder_person_tel())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510006);
			}
			if (StringUtils.isEmpty(req.getOrder_time())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510007);
			}
			if (null == req.getRoom_id()) 
			{
				throw LandseaException.createException(RentalResultCode.E011510008);
			}
			Project project = projectReadMapper.getByRoomId(req.getRoom_id());
			String orderTime = req.getOrder_time().substring(0,10);
			Room room = roomReadMapper.selectRoomInfo(req.getRoom_id());
			if (null != room && null != project) 
			{
				int count = orderReadMapper.selectForRepeat(orderTime, 
						req.getOrder_person_tel(),project.getId());
				if (count > 0) 
				{
					throw LandseaException.createException(RentalResultCode.E011510009);
				}
				else
				{
					//增加预约记录
					Order order = new Order();
					Date orderTime1 = DateUtil.convertDateTime(req.getOrder_time());
					order.setComment(req.getComment());
					order.setOrderPersonName(req.getOrder_person_name());
					if ("1".equals(req.getOrder_person_sex())) 
					{
						order.setOrderPersonSex("_A31");
					}
					else if ("2".equals(req.getOrder_person_sex())) 
					{
						order.setOrderPersonSex("_A32");
					}
					order.setOrderPersonTel(req.getOrder_person_tel());
					order.setOrderTime(orderTime1);

					order.setPrjId(project.getId());
					order.setPrjName(project.getPrjName());
					//支付宝
					order.setOrderFromPage("_LOS3");

					order.setAddress(project.getAreaCode());

					//房间类型
					order.setRoomTypeCode(room.getRoomType());
					if (null != room.getRoomType()) 
					{
						Code code = codeReadMapper.selectByPrimaryKey(room.getRoomType());
						order.setRoomTypeName(code.getCodeDescZh());
					}

					order.setCreatedDtm(new Timestamp(new Date().getTime()));
					order.setCreatedBy(-1);
					order.setLastModifiedBy(-1);
					order.setLastModifiedDtm(new Timestamp(new Date().getTime()));
					order.setVersion(0);
					order.setDeleted(false);
					orderWriteMapper.insertSelective(order);
					Integer orderId = order.getId();
					String orderCode = null;
					String dateNowStr = DateUtil.convertYMDDate(new Date());
					if (orderId < 10) {
						orderCode = "FR" + dateNowStr + "00" + orderId;
					} else if (orderId >= 10 && orderId < 100) {
						orderCode = "FR" + dateNowStr + "0" + orderId;
					} else if (orderId >= 100) {
						orderCode = "FR" + dateNowStr + orderId;
					}
					order.setOrderCode(orderCode);
					orderWriteMapper.updateByPrimaryKeySelective(order);

					//发送短信
					OrderDTO dto = new OrderDTO();
					dto.setOrderPersonName(req.getOrder_person_name());
					dto.setOrderPersonSex(order.getOrderPersonSex());
					dto.setOrderPersonTel(dto.getOrderPersonTel());
					dto.setPrjId(project.getId());
					dto.setPrjName(project.getPrjName());
					dto.setOrderTime(orderTime1);
					sendMessage(dto);
				}

			}		
		}
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			logger.error("预约信息上报失败.", e);
			throw LandseaException.createException(RentalResultCode.E011510002, e);
		}
	}

	public void sendMessage(OrderDTO dto) throws LandseaException {

		//尊敬的李艳艳先生，您已成功预约朗诗寓新街口店，诚邀您于2017-06-20莅临南京市秦淮区中山东路56号新华书店大厦（近洪武路）现场看房。联系电话：0519-88888888、18105179303。
		String name = dto.getOrderPersonName();

		Code code = new Code();
		if (null != dto.getOrderPersonSex()) 
		{
			code = codeReadMapper.selectByPrimaryKey(dto.getOrderPersonSex());

			if(code != null) {
				name += code.getCodeDescTr();
			}
		}
		String prjName = dto.getPrjName();
		int prjId = dto.getPrjId();

		String date = new DateUtil().convertDate3(dto.getOrderTime());
		ProjectDetailDTO projectDto = projectReadMapper.getProjectDetail(prjId);
		//项目地址、电话、店长电话不可为空
		String address = "";
		String phone = "";
		String mobile = "";
		if (projectDto != null) {
			StringBuffer fullAddress = new StringBuffer();

			if (projectDto.getAddressId() != null) {
				AddressDto addressDto = addressService.queryDetailById(projectDto.getAddressId());
				if (addressDto != null) {
					fullAddress.append(addressDto.getCity() == null ? "" : addressDto.getCity()).append(addressDto.getCounty() == null ? "" : addressDto.getCounty()).append(addressDto.getAddressLine() == null ? "" : addressDto.getAddressLine());

				}
			}
			fullAddress.append("现场看房");
			address = fullAddress.toString();
			phone = projectDto.getTelephone();
			mobile = projectDto.getChargeUserMobile();

			//Changed by Daniel for phone settings
			if(StringUtils.isEmpty(phone)) {
				if (!StringUtils.isEmpty(mobile)) {
					phone = mobile;
				}
			} else {
				if (!StringUtils.isEmpty(mobile)) {
					phone += "、" + mobile;
				}
			}

		}
		if (phone == null) {
			phone = "";
		} //优化短信显示

		//String messageCode, String cellPhone, String params
		String params = " {'project':'" + prjName + "','date':'" + date + "','address':'" + address + "','contact':'" + phone + "'}";
		//尊敬的${name}，您已成功预约朗诗寓${project}，诚邀您于${date}莅临${address}。联系电话：${contact}。
		String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
		SMSUtil.sendSms(sendMsgConfiguration.getOrderSuccessCode(), dto.getOrderPersonTel(), params,signName);
	}

	public boolean verifyUpload(UploadOrderInfoReq req) throws LandseaException {
		try
		{
			boolean result = true;
			if (StringUtils.isEmpty(req.getAuthentication())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510011);
			}
			String key = shijiPaymentConfig.getGetProjectInfokey();
			UploadVerifyReq verifyReq = new UploadVerifyReq();
			verifyReq.setComment(req.getComment());
			verifyReq.setOrder_person_name(req.getOrder_person_name());
			verifyReq.setOrder_person_sex(req.getOrder_person_sex());
			verifyReq.setOrder_person_tel(req.getOrder_person_tel());
			verifyReq.setOrder_time(req.getOrder_time());
			verifyReq.setRoom_id(req.getRoom_id());
			String sign = YingShiSignVerifyUtil.
					sign(JsonObjectUtils.bean2JsonObject(verifyReq), key);
			String authentication = YingShiDesUtil.encrypt(sign);
			if (!authentication.equals(req.getAuthentication())) 
			{
				result = false;
			}
			else
			{
				result = true;
			}
			return result;
		}
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			logger.error("秘钥无效.", e);
			throw LandseaException.createException(RentalResultCode.E011510010, e);
		}
	}

	public boolean verifyData(PrjRoomDataReq req) throws LandseaException {
		try
		{
			boolean result = true;
			if (StringUtils.isEmpty(req.getAuthentication())) 
			{
				throw LandseaException.createException(RentalResultCode.E011510011);
			}
			String key = shijiPaymentConfig.getGetProjectInfokey();
			DataVerifyReq verifyReq = new DataVerifyReq();
			verifyReq.setUpdateTime(req.getUpdateTime());
			//获取签名
			String sign = YingShiSignVerifyUtil.
					sign(JsonObjectUtils.bean2JsonObject(verifyReq), key);

			String authentication = YingShiDesUtil.encrypt(sign);

			if (!authentication.equals(req.getAuthentication())) 
			{
				result = false;
			}
			else
			{
				result = true;
			}
			return result;
		}
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			logger.error("秘钥无效.", e);
			throw LandseaException.createException(RentalResultCode.E011510010, e);
		}
	}
}
